/************************************************************************
* tabfill.c
* Copyright (C) Lisa Milne 2013 <lisa@ltmnet.com>
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
* See the GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program.  If not, see <http://www.gnu.org/licenses/>
************************************************************************/

#include "dish.h"
#include "env.h"
#include "path.h"

static char last[CFG_INPUT_BUFFER];
static int last_count = 0;

/* clear the tabfill cache */
void tabfill_clear()
{
	last[0] = 0;
	last_count = 0;
}

/* tab autocompletion */
char* tabfill_get(char* buff)
{
	char* t;
	char* f;
	int e = 0;

	t = tok_last(buff);
	if (!t || !t[0]) {
		last[0] = 0;
		last_count = 0;
		return NULL;
	}

	if (strcmp(last,t)) {
		strcpy(last,t);
		last_count = 0;
	}

	if (t == buff)
		e = 1;
	f = fpath_complete(t,e,last_count);
	if (!f && last_count) {
		last_count--;
		f = fpath_complete(t,e,last_count);
	}
	if (f) {
		last_count++;
		strcpy(t,f);
		strcat(t," ");
		return f;
	}

	return NULL;
}
